<template>
  <div>
    <el-card class="box-card1" :body-style="{ padding: '15px',height: '40px' }" :rules="rules">
      <el-form :inline="true" :model="formInline" class="demo-form-inline" ref="formInline" size="small">
        <el-form-item label="用户名" class="el-form-item-text" prop="username">
          <el-input v-model="formInline.username" size="small" ></el-input>
        </el-form-item>
        <el-form-item label="手机号" class="el-form-item-text" prop="phone">
          <el-input v-model="formInline.phone" size="small"></el-input>
        </el-form-item>
        <el-form-item label="注册时间" class="el-form-item-text" prop="createTime">
          <el-date-picker
              v-model="formInline.createTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              size="small">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" size="small">查询</el-button>
          <el-button @click="resetForm('formInline')" size="small">重置</el-button>
        </el-form-item>

      </el-form>

    </el-card>

    <el-card class="box-card2">
      <div style="display: flex">
        <el-button @click="handleDeleteAll"  size="small" type="danger" plain :disabled="disabled">批量删除</el-button>
        <el-button @click="clearForm();insertFormVisible = true;"  size="small" type="primary" plain>添加</el-button>
      </div>
      <el-dialog title="提示" :visible.sync="insertFormVisible" align="left">
        <el-form :model="userInsertForm" :rules="userInsertRules" ref="userInsertForm" label-width="120px" class="demo-ruleForm" size="small" status-icon>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userInsertForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="userInsertForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPassword">
            <el-input v-model="userInsertForm.checkPassword" type="password"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="userInsertForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-select v-model="userInsertForm.sex" placeholder="请选择">
              <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="insertFormVisible = false" size="small">取 消</el-button>
          <el-button type="primary" @click="handleInsert('userInsertForm')" size="small">确 定</el-button>
        </div>
      </el-dialog>
      <el-table
          ref="multipleTable"
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            prop="username"
            label="用户名"
            width="130">
        </el-table-column>
        <el-table-column
            prop="password"
            label="密码"
            width="130">
        </el-table-column>
        <el-table-column
            prop="phone"
            label="手机号">
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="注册时间">
        </el-table-column>
        <el-table-column
            prop="money"
            label="余额">
        </el-table-column>
        <el-table-column
            prop="sex"
            label="性别"
            width="50"
            align="center">
        </el-table-column>
        <el-table-column
            prop=""
            label="操作"
            align="center"
            width="180">
          <template slot-scope="scope">
            <el-button @click="handleDelete(scope.row.id)"  size="small" type="danger">删除</el-button>
            <el-button @click="handleUpdateFrom(scope.row.id)" size="small" type="primary" >更新</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="提示" :visible.sync="updateForm.updateFormVisible" align="left">
        <el-form :model="userInsertForm" :rules="userUpdateRules" ref="userUpdateForm" label-width="120px" class="demo-ruleForm" size="small" status-icon>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userInsertForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="userInsertForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPassword">
            <el-input v-model="userInsertForm.checkPassword" type="password"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="userInsertForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-select v-model="userInsertForm.sex" placeholder="请选择">
              <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="updateForm.updateFormVisible = false" size="small">取 消</el-button>
          <el-button type="primary" @click="handleUpdate('userUpdateForm')" size="small">确 定</el-button>
        </div>
      </el-dialog>

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="formInline.pageNum"
          :page-sizes="formInline.pageSizes"
          :page-size="formInline.pageSize"
          layout="sizes, prev, pager, next"
          :total="formInline.total">
      </el-pagination>
    </el-card>

  </div>

</template>

<script>
import {userDelete, userGet, userInsert, userUpdate} from "@/api/user";

export default {
  name: "",
  data() {
    var validatePass = (rule, value, callback) => {
      if (value !== this.userInsertForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      //展示及发送的表单内容
      formInline: {
        username: '',
        phone:'',
        createTime:'',
        //分页信息
        pageNum: 1,//当前页
        pageSizes: [3, 6, 9, 12],//每页几条选择器
        pageSize: 6,//每页几条
        total: 0,//总条数
      },
      //添加用户表单
      userInsertForm:{
        id: null,
        username: '',
        password: '',
        checkPassword: '',
        phone: '',
        sex: '',
        createTime: null,
      },
      //搜索框验证规则
      rules:{
        username: [],
        phone: [],
        value1: [],
      },
      //用户插入表单验证规则
      userInsertRules: {
        username:[{
          required: true, message: '请输入用户名', trigger: 'blur'
        }],
        password: [{
          required: true, message: '请输入密码', trigger: 'blur'
        }],
        checkPassword: [{
          required: true, message: '请再次输入密码', trigger: 'blur'
        },{
          validator: validatePass, trigger: 'blur'
        }],
        phone: [{
          min:11, max:11, message: '请输入正确的手机号', trigger: 'blur'
        }],
        sex: [{
          required: true, message: '请选择性别', trigger: 'blur'
        }]
      },
      //用户更新表单验证
      userUpdateRules: {
        checkPassword: [{
          validator: validatePass, trigger: 'blur'
        }],
      },
      //表格数据
      tableData: null,
      //多选信息
      multipleTable: [],
      //是否禁用删除
      disabled: true,
      //添加用户的对话框
      insertFormVisible: false,
      //更新用户的对话框
      updateForm:{
        updateFormVisible: false,
      },
      options: [{
        value: '1',
        label: '男'
      }, {
        value: '2',
        label: '女'
      }],
    }
  },
  methods: {
    //查询按钮
    onSubmit() {
      //console.log(this.formInline.createTime)
      this.getUser();
    },
    //重置按钮
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getUser(){
      userGet(this.formInline).then(res => {
        if (res.code === 200){
          this.$message({message: '查询成功', type: 'success'});
          //console.log(res.data);
          this.tableData = res.data.userList;
          this.formInline.total = res.data.total;
        }else {
          this.$message({message: '查询失败', type: 'info'});
        }
      }).catch(err => {
        this.$message({message: '查询失败', type: 'info'});
      })
    },
    //分页
    handleSizeChange(val) {
      this.formInline.pageSize = val;
      this.getUser();
    },
    handleCurrentChange(val) {
      this.formInline.pageNum = val;
      this.getUser();
    },
    //删除单列
    handleDelete(row) {
      this.deleteUser({idList:row});
    },
    //删除多列
    handleDeleteAll() {
      this.deleteUser({idList:this.multipleTable.join(',')})
    },
    //发送删除用户请求
    deleteUser(data){
      this.$confirm(`将删除${data.idList}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userDelete(data).then(res => {
          if (res.code === 200){
            this.$message({message: '删除成功', type: 'warning'})
            this.getUser();
          }else{
            this.$message({message: '删除失败', type: 'info'})
          }
        }).catch(err => {
          this.$message({message: '删除失败', type: 'info'})
        })
      }).catch(() => {
        this.$message({message: '取消删除', type: 'info'})
      })

    },
    //获得选取列id,同时判断是否禁用删除按钮
    handleSelectionChange(val) {
      this.multipleTable = [];
      for (let valElement of val) {
        this.multipleTable.push(valElement.id)
      }
      this.disabled = this.multipleTable.length === 0;
    },
    //发送添加用户请求
    addUser(data){
      userInsert(data).then(res => {
        if (res.code === 200){
          this.$message({message: '添加成功', type: 'success'})
          this.getUser();
          this.insertFormVisible = false;
        }else {
          this.$message({message: '添加失败', type: 'info'})
        }
      }).catch(err => {
        this.$message({message: '添加失败', type: 'info'})
      })
    },
    //添加用户
    handleInsert(userInsertForm){
      let now = new Date();
      this.userInsertForm.createTime = now.toLocaleDateString();
      this.$refs[userInsertForm].validate((valid) => {
        if (valid) {
          this.addUser(this.userInsertForm);
        } else {
          //console.log('error submit!!');
          return false;
        }
      });
    },
    //发送更新用户请求
    updateUser(data){
      //console.log(this.userInsertForm.id)
      userUpdate(data).then(res => {
        if (res.code === 200){
          this.$message({message: '更新成功', type: 'success'})
          this.getUser();
          this.updateForm.updateFormVisible = false;
        }else {
          this.$message({message: '更新失败', type: 'info'})
        }
      }).catch(err => {
        this.$message({message: '更新失败', type: 'info'})
      })
    },
    //更新用户
    handleUpdate(userUpdateForm){
      this.$refs[userUpdateForm].validate((valid) => {
        if (valid) {
          this.updateUser(this.userInsertForm);
        } else {
          //console.log('error submit!!');
          return false;
        }
      });
    },
    //更新按钮点击事件
    handleUpdateFrom(id){
      this.clearForm();
      this.updateForm.updateFormVisible = true;
      this.userInsertForm.id = id;
    },
    //重置添加或更新用户的表单
    clearForm(){
      this.userInsertForm.id = null;
      this.userInsertForm.username = '';
      this.userInsertForm.password = '';
      this.userInsertForm.checkPassword = '';
      this.userInsertForm.phone = '';
      this.userInsertForm.sex = '';
      this.userInsertForm.createTime = null;
    }


  },
  created() {
    this.getUser();
  }
}
</script>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card1 {
  //width: 480px;
  min-width: 957px;
  height: 65px;
  border-radius: 10px;
}
.box-card2 {
//width: 480px;
  min-width: 957px;
  border-radius: 10px;
  line-height: 10px;
  margin-top: 20px;
}
.el-form-item-text {
  line-height: 0;
}
.demo-form-inline {
  height: 40px;
}
.demo-form-inline .el-input {
  width:120px
}
.demo-ruleForm .el-input,.el-select{
  display: flex;
  width: 240px;
}


</style>